<template>
    <div>
        <Card>

            <Row class="form-row">
                <Form :model="filters" label-position="right" :label-width="90" inline ref="formInline">
                    <FormItem label="小区">
                        <div class="filters-input">
                            <el-select v-model="filters.name" placeholder="请选择小区" filterable clearable
                                       no-data-text="暂无数据">
                                <el-option v-for="item in houseList" :value="item.name" :key="item.name"
                                           :label="item.name"></el-option>
                            </el-select>
                        </div>
                    </FormItem>
                    <FormItem>
                        <Button type="primary" icon="ios-search" @click="handleQuery('formInline')">搜索</Button>
                    </FormItem>
                    <FormItem>
                        <el-button type="primary" @click="WxComentAuth()">授权</el-button>
                    </FormItem>
                </Form>
            </Row>
            <el-table stripe border :loading="tableLoading" :data="tableData" ref="table" style="width: 100%">
                <template slot="empty">暂无数据</template>
                <el-table-column label="公众号名称" prop="nick_name"></el-table-column>
                <el-table-column label="授权公众号ID" prop="biz_appid"></el-table-column>
                <el-table-column label="管理小区" prop="houingNames"></el-table-column>

                <el-table-column label="操作" width="550" align="center">
                    <template slot-scope="scope">
                        <el-button size="mini" type="primary" @click="configure( scope.row.biz_appid )">配置运营小区
                        </el-button>
                        <el-button size="mini" type="primary" @click="menuConfig( scope.row.biz_appid )">微信菜单管理
                        </el-button>
                        <!-- <el-button size="mini" type="primary" @click="sendMsg( scope.row.biz_appid )">推送消息
                         </el-button>-->
                    </template>
                </el-table-column>

            </el-table>

            <Page style="margin: 10px 0;" :total="pageTotal" :current="pageNum" :page-size="pageSize" show-total
                  id="lyPage"
                  show-sizer show-elevator @on-change="handlePage" @on-page-size-change='handlePageSize'>
            </Page>

        </Card>
        <Modal v-model="modalAuth" title="微信公众号授权" width="830">
            <iframe width="800" height="600" id="authIFrame" src=""/>
            <div slot="footer">
                <Button type="text" size="large" @click="onCancel()">关闭</Button>
                <Button type="primary" size="large" @click="handleSubmit" :loading="tableLoading">确定</Button>
            </div>
        </Modal>


        <el-dialog title="配置运营小区" :visible.sync="configureHouse" width="30%">
            <div class="pp-info">
                <el-form :model="configureInfo" :rules="rules" ref="configureForm" label-width="100px"
                         class="demo-ruleForm">
                    <el-form-item label="小区" prop="housingIdArray">
                        <treeselect noChildrenText="没有子节点" noOptionsText="暂无选项"
                                    noResultsText="没有发现结果" placeholder="选择小区" v-model="configureInfo.housingIdArray"
                                    :multiple="true"
                                    :options="treeList"/>
                    </el-form-item>
                </el-form>
            </div>
            <div slot="footer" class="dialog-footer">
                <el-button @click="configureHouse = false">取 消</el-button>
                <el-button type="primary" @click="sureConfigureInfo('configureForm')">确 定</el-button>
            </div>
        </el-dialog>
        <el-dialog title="推送消息" :visible.sync="sendMessage" width="50%">
            <div class="pp-info">

            </div>
            <div slot="footer" class="dialog-footer">
                <el-button @click="sendMessage = false">取 消</el-button>
                <el-button type="primary" @click="sureMessageInfo('messageForm')">确 定</el-button>
            </div>
        </el-dialog>

        <el-dialog title="配置微信菜单" :visible.sync="configureMenu" width="60%" min-height="300px;">
            <el-container style="height: 500px; border: 1px solid #eee">
                <el-aside width="200px" style="background-color: rgb(238, 241, 246)">
                    <el-row class="tac">

                        <!--default-active="key0"-->
                        <el-menu class="el-menu-vertical-demo"

                        >
                            <el-menu-item v-if="btn.sub_button.length == 0" v-for="(btn,index) in menus"
                                          @click="showBtn(btn,'one',index)"
                                          :index="'key'+index">
                                <span slot="title">{{btn.name}}</span>
                            </el-menu-item>

                            <el-submenu v-if="btn.sub_button.length > 0" :index="'key'+index"
                                        v-for="(btn,index) in menus">
                                <template slot="title"> {{btn.name}}</template>
                                <el-menu-item-group v-for="(sbtn,sindex) in btn.sub_button" :key="sindex">
                                    <el-menu-item @click="showBtn(sbtn,'two',index,sindex)" :index="index+'-'+sindex">
                                        {{sbtn.name}}
                                    </el-menu-item>
                                </el-menu-item-group>
                            </el-submenu>

                        </el-menu>

                    </el-row>
                </el-aside>
                <el-container>
                    <div class="menu-tis" v-if="haveNull" style="height: 500px;">
                        <p>请注意</p>
                        <p> 1、自定义菜单最多包括3个一级菜单，每个一级菜单最多包含5个二级菜单。</p>
                        <p>2、一级菜单最多4个汉字，二级菜单最多7个汉字，多出来的部分将会以“...”代替。</p>
                    </div>
                    <div class="menu-info" v-else style="height: 500px;">
                        <el-header style="text-align: right; font-size: 12px">
                            <!--http://192.168.2.12:9096/wechatCommon/wxMenu?gzhId=wxe2f71ea9af8ea232-->
                            <el-button type="primary" size="mini" :disabled="addDisabled">新增一级菜单</el-button>
                            <el-button type="primary" size="mini" :disabled="showSubBtn" @click="addTwoMenu">新增
                            </el-button>
                        </el-header>
                        <el-main>
                            <el-form :model="addButton" ref="btnForm" label-width="100px"
                                     class="demo-ruleForm">
                                <el-form-item class="myclass" label="类型" :disabled="showdisabled">
                                    <el-select v-model="addButton.type" :value="addButton.type">
                                        <el-option value="view">view</el-option>
                                        <el-option value="click">click</el-option>
                                    </el-select>
                                </el-form-item>
                                <el-form-item class="myclass" label="按钮名称">
                                    <el-input v-model="addButton.name" :value="addButton.name"
                                              placeholder="按钮名称"></el-input>
                                </el-form-item>
                                <el-form-item class="myclass" label="KEY" :disabled="showdisabled">
                                    <el-input v-model="addButton.key" :value="addButton.key"
                                              placeholder="KEY"></el-input>
                                </el-form-item>
                                <el-form-item class="myclass" label="跳转地址" :disabled="showdisabled">
                                    <el-input v-model="addButton.url" :value="addButton.url"
                                              placeholder="http://www.siyueluo.com"></el-input>
                                </el-form-item>

                            </el-form>
                            <el-footer style="text-align: right; font-size: 12px">
                                <el-button type="primary" size="mini" @click="delSubMenu">删除</el-button>
                                <el-button type="primary" size="mini" @click="modifySubMenu()">修改</el-button>
                                <el-button type="primary" size="mini" @click="sureSubMenu()" :disabled="sureBtnShow">
                                    确认
                                </el-button>

                            </el-footer>
                        </el-main>
                    </div>

                </el-container>
            </el-container>
            <div slot="footer" class="dialog-footer">
                <el-button @click="configureMenu = false">取 消</el-button>
                <!--<el-button type="primary" @click="sureMenuInfo()">确 定</el-button>-->
            </div>
        </el-dialog>


    </div>
</template>


<script>
    //线上下载模板地址
    import baseURL from "_conf/url";
    import Treeselect from "@riophae/vue-treeselect";
    import Cookies from "js-cookie";
    import {TOKEN_KEY} from "@/libs/util";
    import moment from "moment"
    //线上上传账单地址
    const act = baseURL + "/api/bill/upload";

    export default {
        components: {
            Treeselect,
        },
        data() {
            return {
                //查询条件
                filters: {},
                //页码
                pageNum: 1,
                //每页数量
                pageSize: 10,
                //总数
                pageTotal: 0,
                tableData: [],
                houseList: [],
                msghousingList: [],
                //表单提交状态
                modal: {},
                tableLoading: false,
                modalAuth: false,
                Industry: {},
                choseHousingList: [],
                messageInfo: {},
                configureHouse: false,
                configureMenu: false,
                sendMessage: false,
                treeList: [],
                menuList: [],
                houseList: [],
                menus: [],
                chooseBtn: {},
                housingIdArray: null,
                appId: '',
                addDisabled: false,
                showdisabled: true,
                showSubBtn: false,
                showAddSubBtn: true,
                addButton: {},
                configureInfo: {},
                menuInfo: {},
                number: '',
                //校验规则
                rules: {
                    housingIdArray: [
                        {
                            required: true,
                            message: "请选择小区",
                        }
                    ],
                },
                clickInfo: {},
                haveNull: true,
                sureBtnShow: true,
            }
        },
        created: function () {
            this.gethouse();
            this.loadData();

        },
        methods: {
            //加载数据
            loadData: function () {
                if (this.tableLoading) return;
                this.tableLoading = true;
                let params = this.filters;
                params.pageNum = this.pageNum;
                params.pageSize = this.pageSize;

                // console.log(params)

                //与后台交换数据
                this.getRequest("/api/authInfo/auths?pageNum=" + this.pageNum + "&pageSize=" + this.pageSize).then(res => {
                    this.tableLoading = false;
                    if (res.code == 20000) {
                        this.tableData = res.data.list;
                        this.pageTotal = res.data.total;
                    } else {
                        this.tableData = [];
                        this.$Message.error({
                            content: res.message,
                            duration: 5
                        });
                    }
                });
            },

            //加载小区
            gethouse() {
                let url = "/api/housing/getHousingByLogin";
                this.postRequest(url).then(res => {
                    this.houseList = res;
                });
            },
            handleClick(tab, event) {
                // console.log(tab, event);
            },

            //加载部门树
            treeData() {
                this.getRequest("/api/authInfo/trees").then(res => {
                    if (res.code == 20000) {
                        this.treeList = res.data;
                    } else {
                        this.$Message.error({
                            content: res.message,
                            duration: 5
                        });
                    }
                });
            },
            //加载菜单树
            menuTreeData(appId) {
                this.getRequest("/wechatCommon/wxMenu?gzhId=" + appId).then(res => {
                    if (res.code == 20000) {
                        this.menus = res.data.menu.button;
                        // 把按钮改为可以点击状态
                        this.showSubBtn = false;
                        //初始页面显示的值


                        // //如果只有一级显示当前值
                        // if (this.menus[0].sub_button.length <= 0) {
                        //     this.addButton = this.menus[0];
                        //     console.log(this.addButton);
                        // } else {
                        //     //如果有多级菜单则展示第一条数据
                        //     this.addButton = this.menus[0].sub_button[0];
                        //     console.log(this.addButton);
                        //     //判断菜单长度超过5把按钮改为不可点
                        //     if (this.menus[0].sub_button.length >= 5) {
                        //         this.showSubBtn = true;
                        //     }
                        // }
                        //一级菜单长度
                        if (this.menus.length == 3) {
                            this.addDisabled = true
                        }
                    } else {
                        this.$Message.error({
                            content: res.message,
                            duration: 5
                        });
                    }
                });
            },
            //获取运营的小区
            houseingData(appId) {
                this.getRequest("/wechatCommon/housingList?gzhId=" + appId).then(res => {
                    if (res.code == 20000) {
                        this.msghousingList = res.data;
                    } else {
                        this.$Message.error({
                            content: res.message,
                            duration: 5
                        });
                    }
                });
            },

            //查询
            handleQuery(name) {
                this.loadData();
            },
            handlePage(value) {
                this.pageNum = value;
                this.loadData();
            },
            handlePageSize(value) {
                this.pageSize = value;
                this.loadData();
            },
            onCancel: function () {
                this.modalAuth = false;
                document.getElementById("authIFrame").setAttribute("src", "");
            },
            //获取授权
            WxComentAuth: function () {
                this.modalAuth = true;
                document.getElementById("authIFrame").setAttribute("src", baseURL + "/wechatCommon/toAuth");
            },
            handleSubmit: function () {
                this.modalAuth = false;
                document.getElementById("authIFrame").setAttribute("src", "");
                this.loadData();
            },
            //    配置小区
            configure: function (appId) {
                this.treeData();
                this.configureInfo.appId = appId;
                this.configureHouse = true;
            },
            //    配置菜单
            menuConfig: function (appId) {
                this.menuTreeData(appId);
                this.menuInfo.appId = appId;
                this.configureMenu = true;
            },
            //    推送消息
            sendMsg: function (appId) {
                this.messageInfo = {}
                this.choseHousingList = []
                this.houseingData(appId);
                this.messageInfo.appId = appId;
                this.sendMessage = true;
            },
            showBtn: function (btn, type, index, number) {
                this.addButton = btn;

                //子菜单超过五新增禁用
                // if (this.addButton.sub_button.length >= 5) {
                //     this.showSubBtn = true;
                // }

                if (type == 'one') {
                    this.clickInfo = {
                        type: 'one',
                        index: index,
                    }
                }
                if (type == 'two') {
                    this.clickInfo = {
                        type: 'two',
                        index: index,
                        number: number,
                    }
                    this.showdisabled = false
                }

                this.haveNull = false;
            },

            //添加二级菜单 最多不超过5个人
            addSubMenu: function () {


                if (this.clickInfo.type == 'one') {
                    console.log("这是一级菜单，修改或者添加")
                } else {
                    console.log("这是二级菜单，判断长度是否大于5，小于五则添加")
                }


                //添加二级菜单
                // const number = this.number;
                //
                // this.menus[number].sub_button.push(this.addButton);
                //
                // console.log(this.menus);


            },

            //新增二级菜单按钮
            addTwoMenu: function () {
                this.addButton = {};
                this.sureBtnShow = false;
            },
            //新增菜单
            sureSubMenu: function () {
                if (this.clickInfo.type == "two") {
                    const index = this.clickInfo.index;
                    this.menus[index].sub_button.push(this.addButton);
                    console.log(this.menus);

                    if(this.menus[index].sub_button.length>=5){
                        this.$Message.error({
                            content: "子菜单不能超过5个",
                            duration: 5
                        });
                    }else{
                        this.sureMenuInfo();
                    }

                } else {
                    // alert("此操作将会影响当前菜单");
                    const index = this.clickInfo.index;
                    this.menus[index].sub_button.push(this.addButton);
                    //    网络请求后变为确认按钮变为不可点击
                    // this.sureBtnShow = true;

                    this.$confirm('此操作将会影响当前菜单, 是否继续?', '提示', {
                        confirmButtonText: '确定',
                        cancelButtonText: '取消',
                        type: 'warning'
                    }).then(() => {
                        this.sureMenuInfo();
                    }).catch(() => {

                    });

                    // this.sureMenuInfo();
                }
            },

            //删除菜单
            delSubMenu: function () {
                let index = this.clickInfo.index;
                let number = this.clickInfo.number;
                if (this.clickInfo.type == "two") {
                    this.menus[index].sub_button.splice(number, 1);
                    console.log(this.menus);
                    this.sureMenuInfo();
                } else {
                    this.menus.splice(index, 1)
                    console.log(this.menus);
                    this.sureMenuInfo();
                }
            },
            // 修改菜单
            modifySubMenu: function () {
                let index = this.clickInfo.index;
                let number = this.clickInfo.number;
                if (this.clickInfo.type == "two") {
                    this.menus[index].sub_button[number] = this.addButton;
                    console.log(this.menus);

                    this.sureMenuInfo();

                } else {
                    this.menus[index] = this.addButton;
                    console.log(this.menus);
                    this.sureMenuInfo();

                }



            },

            sureConfigureInfo: function (configureForm) {
                this.$refs[configureForm].validate((valid) => {
                    if (valid) {
                        this.postRequest("/api/authInfo/configCell", this.configureInfo).then(res => {
                            if (res.code == 20000) {
                                this.configureHouse = false;
                                this.$Message.success({
                                    content: "操作成功",
                                    duration: 5
                                });
                                this.getCompanyId(this.filter);
                            } else {
                                this.$Message.error({
                                    content: res.message,
                                    duration: 5
                                });
                            }
                        });
                    }
                });
            },
            sureMessageInfo: function (messageForm) {
                this.$refs[messageForm].validate((valid) => {
                    if (valid) {
                        console.log(this.messageInfo);
                        this.messageInfo.housingList = this.choseHousingList;
                        this.postRequest("/wechatCommon/sendTemplete", this.messageInfo).then(res => {
                            if (res.code == 20000) {
                                this.sendMessage = false;
                                this.$Message.success({
                                    content: "操作成功",
                                    duration: 5
                                });
                            } else {
                                this.$Message.error({
                                    content: res.message,
                                    duration: 5
                                });
                            }
                        });
                    }
                });
            },
            //保存菜单
            sureMenuInfo: function () {
                let params = {}
                // params.gzhId = ''//公众号Id
                params.gzhId = this.menuInfo.appId//公众号Id
                params.menuJson = this.menus//公众号菜单JSON，必须满足微信api接口数据规范
                //确认json正确之前，请勿真实提交
                //确认json正确之前，请勿真实提交
                //确认json正确之前，请勿真实提交
                //确认json正确之前，请勿真实提交
                //确认json正确之前，请勿真实提交
                //确认json正确之前，请勿真实提交
                //确认json正确之前，请勿真实提交
                //确认json正确之前，请勿真实提交
                // return;

                //保存菜单
                this.postRequest("/wechatCommon/saveWxMenu", params).then(res => {
                    if (res.code == 20000) {
                        this.configureMenu = false;
                        this.$Message.success({
                            content: "操作成功",
                            duration: 5
                        });
                        this.sureBtnShow = true;
                    } else {
                        this.$Message.error({
                            content: res.message,
                            duration: 5
                        });
                    }
                });
            }
        }
    };
</script>
<style lang="less" scoped>
    #pop {
        width: 780px;
        height: 600px;
        display: none;
        position: fixed;
        z-index: 10;
        top: 10%;
        left: 50%;
        margin-left: -390px;
    }
</style>
